<template>
	<view class="wrap">
		<view class="top"></view>
		<view class="content">
			<view class="title">欢迎登录</view>
			<view>
				<input class="u-border-bottom" type="text" v-model="loginForm.username" placeholder="请输入账号" />
				<view class="tips"></view>
				<input class="u-border-bottom" type="text" v-model="loginForm.password" placeholder="请输入密码" />
				<view class="tips"></view>
				<button @tap="handleLogin" :style="[inputStyle]" class="getCaptcha">立即登录</button>
			</view>
		</view>
		<view class="buttom">
			<view class="loginType">
				<view class="wechat item">
					<view class="icon"><up-icon size="40" name="weixin-fill" color="rgb(83,194,64)"></up-icon></view>
					微信
				</view>
			</view>
			<view class="hint">
				登录代表同意
				<text class="link">用户协议、隐私政策，</text>
				并授权使用您的账号信息（如昵称、头像、收获地址）以便您统一管理
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
 import { register } from '@/api/login';
// import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
// import { authBinding } from '@/api/system/social/auth';
// import { useUserStore } from '@/store/modules/user';
import type { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import { getToken } from '@/utils/auth';
const userStore = useUserStore();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: 'admin',
  password: 'admin123',
  rememberMe: true,
  code: '',
  uuid: ''
} as LoginData);

const loginRules: ElFormRules = {
 // tenantId: [{ required: true, trigger: 'blur', message: '请输入您的租户编号' }],
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
 // code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
// const captchaEnabled = ref(true);
// // 租户开关
// const tenantEnabled = ref(true);

// 注册开关
// const register = ref(false);
const redirect = ref(undefined);
// const loginRef = ref('loginRef');
// // 租户列表
// const tenantList = ref<TenantVO[]>([]);

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);
const inputStyle = computed(() => {
    let style = {};
    if (loginForm.value.username && loginForm.value.password) {
        style.color = "#fff";
        style.backgroundColor = '#f0ad4e'; // Replace with your color value
    }
    return style;
});
const handleLogin = async () => {
 const valid= loginForm.value.username&&loginForm.value.password;
 if (valid) {
   loading.value = true;
   // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
   if (loginForm.value.rememberMe) {
    // localStorage.setItem('tenantId', String(loginForm.value.tenantId));
     uni.setStorageSync('username', String(loginForm.value.username));
     uni.setStorageSync('password', String(loginForm.value.password));
     uni.setStorageSync('rememberMe', String(loginForm.value.rememberMe));
   } else {
     // 否则移除
     uni.removeStorageSync('tenantId');
     uni.removeStorageSync('username');
     uni.removeStorageSync('password');
     uni.removeStorageSync('rememberMe');
   }
   console.log("loginForm<<<<",loginForm.value)
   
  //  register({  tenantId: '000000',
  // username: 'peifang',
  // userType: 'app_user',
  // password: 'cxy666666'})
   // 调用action的登录方法
   const [err] = await to(userStore.login(loginForm.value));
   console.log("loginApi=====err=>",err)
   if (!err) {
     const redirectUrl = redirect.value || '/';
	setTimeout(()=>{
		uni.switchTab({
			url:"/pages/index/index"
		})
	},500)
     loading.value = false;
   } else {
     loading.value = false;
     // // 重新获取验证码
     // if (captchaEnabled.value) {
     //   await getCode();
     // }
   }
 } else {
  // console.log('error submit!', fields);
 }
};

/**
 * 获取验证码
 */
// const getCode = async () => {
//   const res = await getCodeImg();
//   const { data } = res;
//   captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
//   if (captchaEnabled.value) {
//     codeUrl.value = 'data:image/gif;base64,' + data.img;
//     loginForm.value.uuid = data.uuid;
//   }
// };

const getLoginData = () => {
  const tenantId =  uni.getStorageSync('tenantId') || '000000';
  const username = uni.getStorageSync('username');
  const password = uni.getStorageSync('password');
  const rememberMe = uni.getStorageSync('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  } as LoginData;
};

/**
 * 获取租户列表
 */
// const initTenantList = async () => {
//   const { data } = await getTenantList();
//   tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
//   if (tenantEnabled.value) {
//     tenantList.value = data.voList;
//     if (tenantList.value != null && tenantList.value.length !== 0) {
//       loginForm.value.tenantId = tenantList.value[0].tenantId;
//     }
//   }
// };

//检测租户选择框的变化
// watch(
//   () => loginForm.value.tenantId,
//   () => {
//     localStorage.setItem('tenantId', String(loginForm.value.tenantId));
//   }
// );

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  // authBinding(type).then((res: any) => {
  //   if (res.code === HttpStatus.SUCCESS) {
  //     // 获取授权地址跳转
  //     window.location.href = res.data;
  //   } else {
  //     ElMessage.error(res.msg);
  //   }
  // });
};

onMounted(() => {
  // getCode();
  // initTenantList();
  getLoginData();
});
</script>

<style lang="scss" scoped>
.wrap {
	font-size: 28rpx;
	.content {
		width: 600rpx;
		margin: 80rpx auto 0;

		.title {
			text-align: left;
			font-size: 60rpx;
			font-weight: 500;
			margin-bottom: 100rpx;
		}
		input {
			text-align: left;
			margin-bottom: 10rpx;
			padding-bottom: 6rpx;
		}
		.tips {
			color: $u-info;
			margin-bottom: 60rpx;
			margin-top: 8rpx;
			font-size: 12px;
		}
		.getCaptcha {
			background-color: rgb(253, 243, 208);
			color: $u-tips-color;
			border: none;
			font-size: 30rpx;
			padding: 12rpx 0;
			
			&::after {
				border: none;
			}
		}
		.alternative {
			color: $u-tips-color;
			display: flex;
			justify-content: space-between;
			margin-top: 30rpx;
		}
	}
	.buttom {
		.loginType {
			display: flex;
			padding: 350rpx 150rpx 150rpx 150rpx;
			justify-content:center;
			
			.item {
				display: flex;
				flex-direction: column;
				align-items: center;
				color: $u-content-color;
				font-size: 28rpx;
			}
		}
		
		.hint {
			padding: 20rpx 40rpx;
			font-size: 20rpx;
			color: $u-tips-color;
			
			.link {
				color: $u-warning;
			}
		}
	}
}
</style>
